import React, { useEffect, useState } from 'react'
import { useRoutes, Navigate } from 'react-router-dom'
import axios from '../utils/request'
import PubSub from 'pubsub-js'
interface IRight {
  key: string
  label: string
  id: number
  grade: number
  children?: IRight[]
  pagepermisson?: number
  rightId?: number
}
export default function Router() {
  const [routeList, setRouteList] = useState<IRight[]>([])
  function getData() {
    Promise.all([axios.get('/rights').then(({ data }) => data), axios.get('/children').then(({ data }) => data)]).then((res) => {
      setRouteList([...res[0], ...res[1]])
    })
  }
  useEffect(() => {
    getData()
    const pubId = PubSub.subscribe('updRoute',() => getData())
    return () => {PubSub.unsubscribe(pubId)}
  }, [])
  const currentUser = JSON.parse(localStorage.getItem('token') as string)
  const AuthComponent: React.FC<IAuth> = ({ children, right }) => {
    const isAuth = currentUser.role.rights.includes(right) && routeList.find((item) => item.key === right)?.pagepermisson === 1
    return isAuth ? children : LazyLoad('views/404')
  }
  const element = useRoutes([
    {
      path: '/',
      element: <IsLoginComponent>{LazyLoad('views/NewsSandBox')}</IsLoginComponent>,
      children: [
        {
          path: '',
          element: <Navigate to="/home" />,
        },
        {
          path: 'home',
          //   element: LazyLoad('views/Home'),
          element: <AuthComponent right="/home">{LazyLoad('views/Home')}</AuthComponent>,
        },
        {
          path: 'user-manage/list',
          element: LazyLoad('Components/Menus/UserList'),
        },
        {
          path: 'right-manage/role/list',
          element: LazyLoad('Components/Menus/RoleList'),
        },
        {
          path: 'right-manage/right/list',
          element: LazyLoad('Components/Menus/RightList'),
        },
        {
          path: 'news-manage/add',
          element: LazyLoad('Components/Menus/News-Manage/NewsAdd'),
        },
        {
          path: 'news-manage/draft',
          element: LazyLoad('Components/Menus/News-Manage/NewsDraft'),
        },
        {
          path: 'news-manage/category',
          element: LazyLoad('Components/Menus/News-Manage/NewsCategory'),
        },
        {
          path: 'audit-manage/audit',
          element: LazyLoad('Components/Menus/Audit-Manage/Audit'),
        },
        {
          path: 'audit-manage/list',
          element: LazyLoad('Components/Menus/Audit-Manage/AuditList'),
        },
        {
          path: 'publish-manage/unpublished',
          element: LazyLoad('Components/Menus/Publish-Manage/Unpublished'),
        },
        {
          path: 'publish-manage/published',
          element: LazyLoad('Components/Menus/Publish-Manage/Published'),
        },
        {
          path: 'publish-manage/sunset',
          element: LazyLoad('Components/Menus/Publish-Manage/Sunset'),
        },
        {
          path: '*',
          element: LazyLoad('views/404'),
        },
      ],
    },
    {
      path: '/login',
      element: LazyLoad('views/Login'),
    },
  ])
  return element
}

interface IProps {
  children: JSX.Element
}
interface IAuth {
  children: JSX.Element
  right: string
}
const IsLoginComponent: React.FC<IProps> = ({ children }) => {
  const isLogin = localStorage.getItem('token')
  return isLogin ? children : <Navigate to="/login" />
}

const LazyLoad = (path: string) => {
  const Comp = React.lazy(() => import(`../${path}`))
  return (
    <React.Suspense fallback={<>加载中....</>}>
      <Comp />
    </React.Suspense>
  )
}
